# -*- coding: utf-8 -*-
import subprocess
import re
import MySQLdb as mysql
import time
import socket

#获取mysql数据游标,通过游标操作数据库
db = mysql.connect(user="root", passwd="123",host="localhost", db="EBANK", charset="utf8")
db.autocommit(True)
cur = db.cursor()

"""
   Mac系统各应用程序占内存信息
"""
def processesUseMeminfo():
    ps = subprocess.Popen(['ps', '-caxm', '-orss,comm'], stdout=subprocess.PIPE).communicate()[0]
    processLines = ps.split('\n')
    print  processLines
    sep = re.compile('[\s]+')
    rssTotal = 0 # kB
    for row in range(1,len(processLines)):
       rowText = processLines[row].strip()
       rowElements = sep.split(rowText)
       try:
          rss = float(rowElements[0]) * 1024
       except:
          rss = 0 # ignore...
       rssTotal += rss
    return  rssTotal

"""
   Mac内存活动信息
"""
def processVM():
    vm = subprocess.Popen(['vm_stat'], stdout=subprocess.PIPE).communicate()[0]
    vmLines = vm.split('\n')
    sep = re.compile(':[\s]+')
    vmStats = {}
    for row in range(1,len(vmLines)-2):
        rowText = vmLines[row].strip()
        rowElements = sep.split(rowText)
        vmStats[(rowElements[0])] = int(rowElements[1].strip('\.'))/1024
    return vmStats

def memory_stat():
    mem = {}
    f = open("/proc/meminfo")
    lines = f.readlines()
    f.close()
    for line in lines:
        if len(line) < 2: continue
        name = line.split(':')[0]
        var = line.split(':')[1].split()[0]
        mem[name] = long(var) * 1024.0
    mem['MemUsed'] = mem['MemTotal'] - mem['MemFree'] - mem['Buffers'] - mem['Cached']
    return mem

"""
   执行更新数据库中内存信息,供web展示内存的实时数据
"""
erval = 0
def execute():
    '''更新内存活动信息'''
    global erval
    try:
        ip = socket.gethostbyname(socket.gethostname()) #获取本机ip
        #ip = '10.21.8.10'
        #vmStats = processVM()
        memstat = memory_stat()


        wired = memstat['MemUsed']
        active = memstat['MemTotal']
        free = memstat['MemFree']
        inactive = memstat['Cached']
        t = int(time.time())
        sql = "insert into stat(host,mem_free,mem_usage,mem_total,load_avg,time) VALUES ('%s','%d','%d','%d','%d','%d')"\
              %(ip,wired,active,free,inactive,t)
        print sql
        cur.execute(sql)
        erval += 1
        if erval > 50:
            del_sql = "delete from stat where time < %d "%t
            print '执行数据清理.',del_sql
            cur.execute(del_sql)
            erval = 0

    except Exception , message :
        print '获取内存信息异常:',message
        #pass
    finally:
        pass


    '''更新'''
    #TODO
    #rssTotal = processesUseMeminfo()

#死循环不停的读取内存，每一秒钟插入一条新的内存信息
while True:
    time.sleep(0.1)
    execute()
    print 'none.'
